#!/usr/bin/env python3

import asyncio
import logging
from typing import Any, Sequence
from mcp.server.server import Server
from mcp.server.models import InitializationOptions, NotificationOptions
import mcp.server.stdio
import mcp.types as types

from mcp.tools.convert_tool import ConvertTool
from mcp.handlers.conversion import ConversionHandler
from shared.config import settings

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("md2ppt-mcp")

# 创建 MCP 服务器
server = Server("md2ppt")

# 创建处理器
conversion_handler = ConversionHandler()


@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
    """列出可用的工具"""
    tools_def = ConvertTool.get_tools()
    
    tools = []
    for tool_def in tools_def:
        tools.append(
            types.Tool(
                name=tool_def["name"],
                description=tool_def["description"],
                inputSchema=tool_def["inputSchema"]
            )
        )
    
    return tools


@server.call_tool()
async def handle_call_tool(
    name: str, arguments: dict[str, Any] | None
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
    """处理工具调用"""
    if arguments is None:
        arguments = {}
    
    logger.info(f"Tool called: {name} with arguments: {arguments}")
    
    try:
        if name == "convert_markdown_to_ppt":
            result = await conversion_handler.handle_convert_markdown_to_ppt(arguments)
        elif name == "convert_markdown_file_to_ppt":
            result = await conversion_handler.handle_convert_markdown_file_to_ppt(arguments)
        elif name == "get_supported_themes":
            result = await conversion_handler.handle_get_supported_themes(arguments)
        elif name == "validate_markdown":
            result = await conversion_handler.handle_validate_markdown(arguments)
        else:
            raise ValueError(f"Unknown tool: {name}")
        
        # 转换结果为 MCP 类型
        mcp_result = []
        for item in result:
            if item["type"] == "text":
                mcp_result.append(types.TextContent(type="text", text=item["text"]))
        
        return mcp_result
        
    except Exception as e:
        logger.error(f"Tool execution error: {e}")
        return [
            types.TextContent(
                type="text", 
                text=f"❌ Error executing tool '{name}': {str(e)}"
            )
        ]


async def main():
    """主函数"""
    logger.info(f"Starting MD2PPT MCP Server v{settings.api_version}")
    
    # 使用 stdio 传输运行服务器
    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="md2ppt",
                server_version=settings.api_version,
                capabilities=server.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                ),
            ),
        )


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("MD2PPT MCP Server shutdown")
    except Exception as e:
        logger.error(f"Server error: {e}")
        raise